<?php
namespace control;
/*
*开票类
*/

class openInvoiceClass extends adIndexClass
{
    private const page = 'openInvoice';
    private const table = 'invoice_open';
    private const table_mx = 'invoice_open_detail';
    private const title = '开票';
    private string $addIco = root . 'img/control/v_add.svg';
    private string $delIco = root . 'img/control/v_del.svg';
    public string $cla = 'openInvoice';
    public string $switch_ico = root . 'img/control/switch.svg';

    /*列表-查询条件*/
    public function home()
    {
        return $this->room();
    }

    /**
     * 发票单价小数位数
     * @return int
     */
    public static function priceDecimal(): int
    {
        $setting = optionSettingClass::getSetting('总账');
        return $setting['invoicePrice'] ?? 4;
    }

    /**
     * 计算税额
     */
    public function calculateTax($isTax, $money, $tax = 0): float
    {
        if ($isTax) {
            //含税
            $taxMoney = round($money * $tax / (1 + $tax), 2);
        } else {
            $taxMoney = round($money * $tax, 2);
        }
        return $taxMoney;
    }

    /**
     * 编辑
     */
    public function editEdit()
    {
        $href = $this->get('href');
        $id = $this->post('id') ?: self::getId();
        $models = $this->post('model');
        $names = $this->post('name');
        $units = $this->post('unit');
        $nums = $this->post('num');
        $prices = $this->post('price');
        $moneys = $this->post('money') ?: [];
        $taxs = $this->post('tax') ?: [];
        $mxIds = $this->post('mxId');
        $sourceIds = $this->post('sourceId');
        $field = [
            'buyCompany' => $this->post('clientName'),
            'classify' => $this->post('invoiceType'),
            'buyTaxNo' => $this->post('buyTaxNum'),
            'buyAddress' => $this->post('buyAddress'),
            'buyBank' => $this->post('buyBankName'),
            'checkName' => $this->post('checkName'),
            'receiveName' => $this->post('receiveName'),
            'createName' => $this->post('createName'),
            'invoiceDate' => $this->post('invoiceDate'),
            'invoiceCode' => $this->post('invoiceCode'),
            'invoiceNo' => $this->post('invoiceNo'),
            'secret' => $this->post('secret'),
            'khid' => $this->post('khid'),
            'isTax' => $this->post('isTax'),
            'saleCompany' => $this->post('saleCompany'),
            'saleTaxNo' => $this->post('saleTaxNum'),
            'saleAddress' => $this->post('saleAddress'),
            'saleBank' => $this->post('saleBankName'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'invoiceDate' => L('finance.table.kai_piao_ri_qi'),
            'invoiceCode' => L('finance.table.fa_piao_dai_ma'),
            'invoiceNo' => L('finance.table.fpbh'),
            'buyCompany' => L('finance.table.ghdwmc'),
            'buyTaxNo' => L('finance.table.ghdwnsrsbh'),
            'saleCompany' => L('finance.table.xhdw'),
            'saleTaxNo' => L('finance.table.xhdwnsrsbh'),
        ];
        $rules = [
            'invoiceDate' => 'required',
            'invoiceCode' => 'required',
            'invoiceNo' => 'required',
            'buyCompany' => 'required',
            'buyTaxNo' => 'required',
            'saleCompany' => 'required',
            'saleTaxNo' => 'required',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power('openInvoice', "edit") && !$this->power('saleInvoice', "edit")) {
            $json['warn'] = L('finance.table.openInvoice_edit');
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = L('finance.table.qtxfpnr');
        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and type = '开票' and invoiceNo = '$field[invoiceNo]' and id !='$id'")) > 0) {
            $json['warn'] = L('finance.table.yczcfphm');
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'type' => '开票',
                    'state' => '正常',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //选项设置
            $totalMoney = $taxTotalMoney = 0;
            $ids = [];
            foreach ($mxIds as $k => $mxId) {
                if ($names[$k]) {
                    $prices[$k] = $prices[$k] ? round($prices[$k], self::priceDecimal()) : 0;
                    $detail = query(self::table_mx, "id = '$mxId'");
                    $ids[] = $mxId;
                    if (empty($moneys[$k]) || !is_numeric($moneys[$k])) {
                        $json['warn'] = str_replace(['{{x}}'], [$k + 1], L('finance.table.openInvoice_edit_warn'));
                        break;
                    }
                    $baseUnit = currencyClass::calculateDecimal($prices[$k]);
                    $taxMoney = $this->calculateTax($field['isTax'], $moneys[$k], $taxs[$k] / 100);
                    if (empty($detail['id'])) {
                        $warn = static::insert(array(
                            'table' => self::table_mx,
                            'field' => [
                                'id' => $mxId,
                                'coid' => self::$coid,
                                'orderId' => $id,
                                'name' => $names[$k],
                                'model' => $models[$k],
                                'unit' => $units[$k],
                                'price' => $prices[$k] * $baseUnit,
                                'baseUnit' => $baseUnit,
                                'num' => $nums[$k],
                                'money' => $moneys[$k],
                                'tax' => $taxs[$k] / 100,
                                'taxMoney' => $taxMoney,
                                'sourceId' => $sourceIds[$k],
                                'sourceTable' => 'sale_send_order_detail'
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::table_mx,
                            'field' => [
                                'name' => $names[$k],
                                'model' => $models[$k],
                                'unit' => $units[$k],
                                'price' => $prices[$k] * $baseUnit,
                                'baseUnit' => $baseUnit,
                                'num' => $nums[$k],
                                'money' => $moneys[$k],
                                'tax' => $taxs[$k] / 100,
                                'taxMoney' => $taxMoney,
                                'sourceId' => $sourceIds[$k],
                                'sourceTable' => 'sale_send_order_detail'
                            ],
                            'where' => "id = '$detail[id]'"
                        ));
                    }
                    $taxTotalMoney += $taxMoney;
                    $totalMoney += $moneys[$k];
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            $unTaxMoney = $field['isTax'] ? ($totalMoney - $taxTotalMoney) : $totalMoney;
            $totalMoney = !$field['isTax'] ? ($totalMoney + $taxTotalMoney) : $totalMoney;
            $warn = update(array('table' => self::table, 'field' => ['money' => $totalMoney, 'unTaxMoney' => $unTaxMoney, 'taxMoney' => $taxTotalMoney], 'where' => "id = '$id'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::table_mx, "where" => "id not in ('" . implode("','", $ids) . "') and orderId = '$id'"));
                //添加日志
                $text = str_replace(['{{staffName}}', '{{invoiceNo}}', '{{id}}'], [$this->control['name'], $field['invoiceNo'], $id], L('finance.table.openInvoice_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                if ($href == 'new') {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
                } else {
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&id=" . $id;
                }
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    public function vatInvoiceVerify()
    {

        $html = $this->layerEdit(array("table" => array(
            array(
                L('finance.table.shuo_ming') . "：" => L('finance.table.gjtxdxlnrzdhqfpxx'),
            ),
            array(
                must . L('finance.table.fa_piao_dai_ma') . "：" => text(array('name' => 'invoiceCode', 'value' => $this->post('invoiceCode'))),
            ),
            array(
                must . L('finance.table.fa_piao_hao_ma') . "：" => text(array('name' => 'invoiceNo', 'value' => $this->post('invoiceNo')))
            ),
            array(
                must . L('finance.table.fa_piao_ri_qi') . "：" => text(array('name' => 'invoiceDate', 'laydate' => [], 'value' => $this->post('invoiceDate'))),
            ),
            array(
                L('finance.table.money_text') . "：" => "<p>".L('finance.table.descriptionOne')."</p>
                                <p>".L('finance.table.descriptionTwo')."</p>
                                <p>".L('finance.table.descriptionThree')."</p>
                                <p>".L('finance.table.descriptionFour')."</p>
                                <p>".L('finance.table.descriptionFive')."</p>
                                <p>".L('finance.table.descriptionSix')."</p>",
            ),
            array(
                must . L('finance.table.jehfpxym') ."：" => text(array('name' => 'additional'))
            ),
        )
        ));
        //返回
        return $this->layer(array(
            "title" => L('finance.table.fa_piao_he_yan'),
            "height" => 500,
            'width' => 850,
            "html" => $html,
            'button' => "<input onclick=\"vatInvoiceVerify('openInvoiceVatInvoiceVerifyForm',root+'control/adIndex.html?cla=openInvoice&fun=vatInvoiceVerifyEdit')\" type=\"button\" class=\"button\" value=\"".L('finance.table.confirm')."\">"
        ));
    }

    public function vatInvoiceVerifyEdit()
    {

        $field = [
            'invoiceCode' => $this->post('invoiceCode'),
            'invoiceNo' => $this->post('invoiceNo'),
            'invoiceDate' => $this->post('invoiceDate'),
            'additional' => $this->post('additional'),
        ];
        $annotation = [
            'invoiceCode' => L('finance.table.fa_piao_dai_ma'),
            'invoiceNo' => L('finance.table.fa_piao_hao_ma'),
            'idCard' => L('finance.table.fa_piao_ri_qi'),
            'additional' => L('finance.table.jehfpxym'),
        ];
        $rules = [
            'invoiceCode' => 'required',
            'invoiceNo' => 'required',
            'invoiceDate' => 'required|date',
            'additional' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $tencent = new tencentApiClass();
            $result = $tencent->vatInvoiceVerify($field['invoiceCode'], $field['invoiceNo'], $field['invoiceDate'], $field['additional']);
            $res = json_decode($result, true);
            if (isset($res['Response']['Error'])) {
                $json['warn'] = $res['Response']['Error']['Message'];
            } else {
                $dataTr = '';
                foreach ($res['Response']['Invoice']['Items'] as $array) {
                    $mxId = suiji();
                    $array['TaxRate'] = rtrim($array['TaxRate'], '%');
                    $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'value' => $array['TaxRate'])) . "</select>";
                    $dataTr .= <<<eof
<tr class="tr-data td-data center">
      <td>
      <input name="mxId[]"  type="hidden" value="$mxId">
      <input type="hidden" name="sourceId[]" value="">
      <div class="add_v_btn"><img src="{$this->addIco}"></div>
      <input name="name[]" value="{$array['Name']}" id="$mxId" type="text" class="width_100">
      </td>
            <td><input name="model[]" value="{$array['Spec']}" type="text" class="width_100"></td>
            <td><input name="unit[]" value="{$array['Unit']}" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" value="{$array['Quantity']}" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" value="{$array['UnitPrice']}" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" value="{$array['AmountWithoutTax']}" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly value="{$array['TaxAmount']}" type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
<script>
        $("#{$mxId}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
              $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
eof;
                }
                unset($res['Response']['Invoice']['Items']);
                $res['Response']['Invoice']['Date'] = date('Y-m-d', strtotime($res['Response']['Invoice']['Date']));
                $json['data'] = [
                    'html' => $dataTr,
                    'info' => $res['Response']['Invoice']
                ];
                $json['warn'] = 2;
            }
        }

        return json_encode($json, 320);
    }

    /**
     * 开票
     * @return string
     */
    public function room(): string
    {
        $id = $this->get('id');
        $info = query(self::table, "id = '$id'");
        //上一张号码
        $preInvoice = query('invoice_open', "coid = '" . self::$coid . "' and type = '开票' and classify = '普票' order by time desc");
        $info['invoiceCode'] = $info['id'] ? $info['invoiceCode'] : $preInvoice['invoiceCode'];
        if (!$info['id'] && $preInvoice['id'] && preg_match(checkInteger,$preInvoice['invoiceNo']) !=0) {
            $info['invoiceNo'] = $preInvoice['invoiceNo'] + 1;
        }

        if (!$info['id']) {
            //带出账套的发票信息
            $company = query('company', "coid = '" . self::$coid . "'");

            $info['saleCompany'] = $company['invoiceCompany'];
            $info['saleTaxNo'] = $company['invoiceNo'];
            $info['saleAddress'] = $company['addressAndTel'];
            $info['saleBank'] = $company['bankName'];
        }

        $recordDate = text(array('name' => 'invoiceDate', 'class' => 'height23', 'laydate' => [], 'value' => $info['invoiceDate'] ?: $this->date));
        $isTax = $info['isTax'] ? 'checked' : '';
        $ocr =  L('finance.table.ocr');
        $openAndAdd = L('finance.table.openAndAdd');
        $openInvoice = L('finance.table.openInvoice');
        $relativeNo = L('finance.table.relativeNo');
        $invoiceCodeText = L('finance.table.fa_piao_dai_ma');
        $openDateText = L('finance.table.kai_piao_ri_qi');
        $taxText = L('finance.table.tax');
        $topButton = <<<eof
    <div class="voucher-button">
        <span class="spanButton li-btn-blue-bg" style="margin-left: 0" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=openInvoice&fun=editEdit&href=new')">$openAndAdd</span>
        <span class="spanButton" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=openInvoice&fun=editEdit&href=save')">$openInvoice</span>
        <span class="spanButton" onclick="layer('openInvoice','vatInvoiceOCR',{})">$ocr</span>
        <span class="spanButton" onclick="chooseOrder()">$relativeNo</span>
    </div>
    <div class="input-div">
    {$invoiceCodeText}：<input class="voucherNo" name="invoiceCode" type="text" value="{$info['invoiceCode']}">&nbsp; <span style="margin-left: 20px">{$openDateText}：{$recordDate}</span>
    <span style="margin-left: 20px">NO：<input class="voucherNo" name="invoiceNo" type="text" value="{$info['invoiceNo']}"></span>
<span style="padding: 2px;margin-right: 20px" class="right"><label><input name="isTax" $isTax value="1" type="checkbox" />&nbsp;$taxText</label></span>

</div>
eof;

        $dataTr = '';
        $all = find(array('table' => self::table_mx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($all['array'] as $array) {
            $mxId = $array['id'];
            $array['num'] = floatval($array['num']);
            $array['price'] = currencyClass::intToDecimal($array['price'], $array['baseUnit']);
            $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'value' => $array['tax'] * 100)) . "</select>";
            $dataTr .= <<<eof
<tr class="tr-data td-data center">
            <td><input name="mxId[]"  type="hidden" value="$mxId"><input name="sourceId[]" type="hidden" value="$array[sourceId]"><div class="add_v_btn"><img src="{$this->addIco}"></div><input name="name[]" value="{$array['name']}" type="text" class="width_100"></td>
            <td><input name="model[]" value="{$array['model']}" type="text" class="width_100"></td>
            <td><input name="unit[]" value="{$array['unit']}" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" value="{$array['num']}" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" value="{$array['price']}" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" value="{$array['money']}" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly value="{$array['taxMoney']}" type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
eof;
        }
        $all['array'] = $all['array'] ?? [];
        $num = 5 - count($all['array']);
        $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'title' => '', 'value' => '')) . "</select>";
        for ($i = 1; $i <= $num; $i++) {
            $mxId = suiji();
            $dataTr .= <<<eof
      <tr class="tr-data td-data center">
            <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value=""><div class="add_v_btn"><img src="{$this->addIco}"></div><input name="name[]" type="text" class="width_100"></td>
            <td><input name="model[]" type="text" class="width_100"></td>
            <td><input name="unit[]" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]"  readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
eof;
        }
        $info['createName'] = !$info['id'] ? $this->control['name'] : $info['createName'];
        $staffName = "<input name='createName' value='{$info['createName']}'/>";
        $receiveSelect = "<input name='receiveName' value='{$info['receiveName']}'/>";
        $checkSelect = "<input name='checkName' value='{$info['checkName']}'/>";
        $bigNumber = voucherEditClass::num_to_rmb($info['money']);
        $taxHidden = $info['isTax'] ? '' : 'hide';
        $info['classify'] = $info['classify'] ?: '普票';
        $title = $info['classify'] == '普票' ? L('finance.table.zzsptfp') : L('finance.table.zzszyfp');

        $buyText = L('finance.table.gou_huo_dan_wei');
        $bankText = L('finance.table.bank');
        $taxNumText = L('finance.table.taxNum');
        $nameText = L('finance.table.name');
        $addressTelText = L('finance.table.addressTel');
        $secretCodeText = L('finance.table.secretCode');
        $goodsText = L('finance.table.goods');
        $modelText = L('finance.table.gui_ge_xing_hao');
        $unitText = L('finance.table.dan_wei');
        $numText = L('finance.table.shu_liang');
        $priceText = L('finance.table.dan_jia');
        $moneyText = L('finance.table.jin_e');
        $taxRateText = L('finance.table.shui_lu');
        $taxMoneyText = L('finance.table.shui_e');
        $totalText = L('finance.table.he_ji');
        $taxMoneyTotalText = L('finance.table.taxMoneyTotal');
        $saleCompanyText = L('finance.table.xhdw');
        $lowerCaseText = L('finance.table.lowerCase');
        $remarkText = L('finance.table.text');
        $receiveText = L('finance.table.shou_kuan_ren');
        $checkText = L('finance.table.fu_he_ren');
        $openStaffText = L('finance.table.kai_piao_ren');
        $sealText = L('finance.table.seal');
        $data['html'] = <<<efo
<form name="voucherForm">
<div class="voucher-body">
<div class="voucher-title"><span id="invoiceTitle">$title</span><img id="switch_ico" class="switch_ico" src="{$this->switch_ico}"><input name="invoiceType" type="hidden" value="$info[classify]"></div>
<div class="calendarBody">
{$topButton}
    <table class="voucherTable">
      <tr>
        <td colspan="8">
        <div class="td-title">
            <div class="company-title">$buyText</p></div>
            <div style="height: 30px;padding: 5px">
                <div><span>{$nameText}：</span><input name="clientName" value="{$info['buyCompany']}" type="text" style="width: 380px"><input name="khid" value="{$info['khid']}" type="hidden"></div>
                <div><span>{$taxNumText}：</span><input name="buyTaxNum" value="{$info['buyTaxNo']}" type="text" style="width: 380px"></div>
                <div><span>{$addressTelText}：</span><input name="buyAddress"  value="{$info['buyAddress']}"  type="text" style="width: 380px"></div>
                <div><span>{$bankText}：</span><input name="buyBankName" value="{$info['buyBank']}"  type="text" style="width: 380px"></div>
            </div>
            <div class="company-title-two">$secretCodeText</div>
            <div style="padding: 5px 5px 0 5px"><textarea name="secret" style="width: 380px;height: 80px">{$info['secret']}</textarea></div>
        </div>
        </td>
        </tr>
        <tr class="tr-data center">
            <td style="width: 221px">$goodsText</td>
            <td style="width: 120px">$modelText</td>
            <td>$unitText</td>
            <td>$numText</td>
            <td style="width: 95px">$priceText<span class="$taxHidden isTax">($taxText)</span></td>
            <td style="width: 95px">$moneyText<span class="$taxHidden isTax">($taxText)</span></td>
            <td>$taxRateText%</td>
            <td style="width: 95px">$taxMoneyText</td>
        </tr>
      {$dataTr}
      <tr class="tr-data tr-border">
            <td>$totalText</td>
            <td colspan="7"><div style="text-align: left">{$moneyText}：<span id="sumMoney">{$info['unTaxMoney']}</span><span class="right">{$taxMoneyText}：<span id="sumTaxMoney">{$info['taxMoney']}</span></span></div></td>
      </tr>
      <tr class="tr-data">
            <td>$taxMoneyTotalText</td>
            <td colspan="7"><div style="text-align: left"><span id="bigNumber">$bigNumber</span><span class="right">{$lowerCaseText}：<span id="sumTaxAndMoney">{$info['money']}</span></span></div></td>
      </tr>
     <tr>
        <td colspan="8">
        <div class="td-title">
            <div class="company-title">$saleCompanyText</div>
            <div style="height: 30px;padding: 5px">
                <div><span>{$nameText}：</span><input name="saleCompany" value="{$info['saleCompany']}" type="text" style="width: 380px"></div>
                <div><span>{$taxNumText}：</span><input name="saleTaxNum" value="{$info['saleTaxNo']}"  type="text" style="width: 380px"></div>
                <div><span>{$addressTelText}：</span><input name="saleAddress" value="{$info['saleAddress']}"  type="text" style="width: 380px"></div>
                <div><span>{$bankText}：</span><input name="saleBankName" value="{$info['saleBank']}"  type="text" style="width: 380px"></div>
            </div>
            <div class="company-title-two" style="letter-spacing: 15px">$remarkText</div>
            <div style="padding: 5px 5px 0 5px"><textarea name="text" style="width: 380px;height: 80px">{$info['text']}</textarea></div>
        </div>
        </td>
        </tr>
    </table>
    <div class="staffName"><span>{$receiveText}：{$receiveSelect}</span><span style="margin-left: 50px">{$checkText}：{$checkSelect}</span><span style="margin-left: 50px">{$openStaffText}：{$staffName}</span><span class="right" style="margin-right: 60px">$sealText</span></div>
</div>
</div>
<input name="id" value="$id" type="hidden">
<div id="file-list" class="hide file-list"></div>
</form>
<script>
   $("input[name='clientName']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getClient',
        callback:function(data,e){
              $(e).siblings("[name='khid']").val(data.id);
            $("[name='buyTaxNum']").val(data.companyNum);
            $("[name='buyBankName']").val(data.companyBank+data.companyBankNum);
            $("[name='buyAddress']").val(data.companyAddress);
        }
    });
   function chooseOrder(){
       let khid = $("[name='khid']").val();
       if (!khid){
           msg('请先选择购货单位','error')
           return false;
       }
       layer('openInvoice','addSendOrder',$('[name=voucherForm]').serialize())
   }
</script>
efo;
        $data['html'] .= $this->css() . $this->js();
        //返回
        return $this->tab($data);
    }


    public function js(): string
    {
        $numDecimal = self::priceDecimal();//小数位
        $cla = $this->cla;
        $js = <<<eof
<script>
    var phi = 0;
	var camidx = 0; 
	var uuid = "";
	var filepath = "";
	var filelist = "";

$(function() {
   var voucherTable = $(".voucherTable");
   $("[name='isTax']").on('click',function() {
       let isTax;
      if ($(this).is(":checked")){
          $(".isTax").removeClass('hide');
          isTax = 1;
      }else{
          $(".isTax").addClass('hide');
          isTax = 0;
      }
      //计算税额
      let tax,money,taxMoney;
      $("[name='money[]']").each(function() {
         money = Number($(this).val());
         tax = Number($(this).parent().parent().find("[name='tax[]']").val())/100;
         taxMoney = calculateTax(isTax,money,tax);
         $(this).parent().parent().find("[name='taxMoney[]']").val(taxMoney)
      })
       calculateTotal();
   })

   $("[name='name[]']").each(function() {
        $(this).bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
              $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
   })

  //增加，删除图标显示
   voucherTable.on('mouseenter','.td-data,.add_v_btn,.del_v_btn',function(){
         if ($(this).is(".td-data")){
            $(this).find(".add_v_btn,.del_v_btn").show();
        }else{
            $(this).parent().parent().find(".add_v_btn,.del_v_btn").show();
        }
    });
    voucherTable.on('mouseleave','.td-data,.add_v_btn,.del_v_btn',function(){
        $(".add_v_btn,.del_v_btn").hide();
     });
    voucherTable.on('click','.add_v_btn',function() {
      let _this = $(this);
      $.post(root+'control/adIndex.html?cla=$cla&fun=addRow',{},function(res) {
         _this.parent().parent().after(res.html);
      },'json')
    })
    voucherTable.on('click','.del_v_btn',function() {
      $(this).parent().parent().remove();
    })
})  

function vatInvoiceVerify(form,url){
     //防止高频点击
        let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
        //异步提交数据
        $.post(url, serialize, function (data) {
            //console.log(data);
            if (data.warn == 2) {
                $('#openInvoiceVatInvoiceVerify').hide();
                $(".voucherTable .td-data").remove();
                $(".voucherTable tr").eq(1).after(data.data.html);
                setVal(data)
                
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
}
function setVal(data){
                $("[name='invoiceCode']").val(data.data.info.Code);
                $("[name='invoiceNo']").val(data.data.info.Number);
                $("[name='clientName']").val(data.data.info.BuyerName);
                $("[name='buyTaxNum']").val(data.data.info.BuyerTaxCode);
                $("[name='buyAddress']").val(data.data.info.BuyerAddressPhone);
                $("[name='buyBankName']").val(data.data.info.BuyerBankAccount);
                $("[name='saleCompany']").val(data.data.info.SellerName);
                $("[name='saleTaxNum']").val(data.data.info.SellerTaxCode);
                $("[name='saleAddress']").val(data.data.info.SellerAddressPhone);
                $("[name='saleBankName']").val(data.data.info.SellerBankAccount);
                $("[name='text']").val(data.data.info.Remark);
                $("#sumMoney").html(data.data.info.AmountWithoutTax);
                $("#sumTaxMoney").html(data.data.info.TaxAmount);
                $("#sumTaxAndMoney").html(data.data.info.AmountWithTax);
                $("#bigNumber").html(upperMoney(data.data.info.AmountWithTax));
                $("[name='invoiceDate']").val(data.data.info.Date);
}
//计算总金额，总税额
function calculateTotal(){
 
   let isTax = $("[name='isTax']:checked").val();
    let money=0;
    let taxMoney=0;
    $("[name='money[]']").each(function(){
        if($(this).val()){
          money+=Number($(this).val());
          taxMoney+=Number($(this).parent().parent().find("[name='taxMoney[]']").val());
        }
    })
    $("#sumMoney").html(money.toFixed(2));
    $("#sumTaxMoney").html(taxMoney.toFixed(2));
    if(isTax){
       $("#sumTaxAndMoney").html(money.toFixed(2));
        $("#bigNumber").html(upperMoney(money.toFixed(2)));
    }else{
      $("#sumTaxAndMoney").html((money+taxMoney).toFixed(2));
       $("#bigNumber").html(upperMoney((money+taxMoney).toFixed(2)));
    }
}
/***计算税额***/
     function calculateTax(isTax,money,tax){
        let taxMoney;
        if (isTax){
             //含税
             taxMoney = (money*tax/(1+tax)).toFixed(2)
          }else{
              //不含税
              taxMoney = (money*tax).toFixed(2)
          }
        return taxMoney;
     }
    /**计算某一行的金额**/
    function calculateMoney(e){
        let type = $(e).data('type');
        let isTax = $("[name='isTax']:checked").val();
        let price,money,num,tax,taxMoney;
        switch (type) {
          case 'num':
              num = Number($(e).val());
              price = Number($(e).parent().parent().find("[name='price[]']").val());
              tax = Number($(e).parent().parent().find("[name='tax[]']").val())/100;
              money = (price*num).toFixed(2);
              console.log(money)
              taxMoney = calculateTax(isTax,money,tax);
              $(e).parent().parent().find("[name='money[]']").val(money);
              $(e).parent().parent().find("[name='taxMoney[]']").val(taxMoney)
              break;
          case 'price':
              price = Number($(e).val());
              num = Number($(e).parent().parent().find("[name='num[]']").val());
              tax = Number($(e).parent().parent().find("[name='tax[]']").val())/100;
              money = price && num ?(price*num).toFixed(2):'';
              taxMoney = calculateTax(isTax,money,tax);
              $(e).parent().parent().find("[name='money[]']").val(money);
              $(e).parent().parent().find("[name='taxMoney[]']").val(taxMoney)
              break;
          case 'money':
              money = Number($(e).val());
              num = Number($(e).parent().parent().find("[name='num[]']").val());
              tax = Number($(e).parent().parent().find("[name='tax[]']").val())/100;
              let decimal = $numDecimal;
              price = num?Number((money/num).toFixed(decimal)):'';
              taxMoney = calculateTax(isTax,money,tax);
              $(e).parent().parent().find("[name='price[]']").val(price);
              $(e).parent().parent().find("[name='taxMoney[]']").val(taxMoney)
              break;
          case 'tax':
              tax = Number($(e).val())/100;
              money = Number($(e).parent().parent().find("[name='money[]']").val());
              taxMoney = calculateTax(isTax,money,tax);
              $(e).parent().parent().find("[name='taxMoney[]']").val(taxMoney)
              break;
        }
        calculateTotal();
    }
    function vatInvoiceOCR(form,url){
     //防止高频点击
        let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
        //异步提交数据
        $.post(url, serialize, function (data) {
            if (data.warn == 2) {
               $('#openInvoiceVatInvoiceOCR').hide();
                $(".voucherTable .td-data").remove();
                $(".voucherTable tr").eq(1).after(data.data.html);
                $("[name='receiveName']").val(data.data.info.receiveName);
                $("[name='checkName']").val(data.data.info.checkName);
                $("[name='createName']").val(data.data.info.openName);
                $("[name='secret']").val(data.data.info.secret1+data.data.info.secret2+data.data.info.secret3+data.data.info.secret4)
                setVal(data)
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
}
</script>
eof;
        $js .= $this->js2();
        return $js;
    }

    public function js2(): string
    {
        $invoiceP = L('finance.table.zzsptfp');
        $invoiceZ = L('finance.table.zzszyfp');
        return <<<eof
<script>
 $("#switch_ico").on('click',function() {
    let type = $("[name='invoiceType']").val();
    if (type=='普票'){
        $("#invoiceTitle").html('$invoiceZ');
        $("[name='invoiceType']").val('专票');
       
    }else{
         $("[name='invoiceType']").val('普票')
          $("#invoiceTitle").html('$invoiceP');
    }
     $(".calendarBody").addClass("animated fadeInRight")
     setTimeout(function() {
         $(".calendarBody").removeClass("animated fadeInRight")
     },1000)
 })
 function commitPhotograph(form,url){
        let con = setTimeout(function (){
            $("#loading", window.top.document).hide();
        },15000);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
        //异步提交数据
        $.post(url, serialize, function (data) {
            if (data.warn == 2) {
                $('#openInvoicePhotograph').hide();
                // $("#photoFile").empty().append(data.html);
                $("[name='fileId']").val(data.data.id);
                $("#upload-ico").attr('src', root + "img/control/delete.svg");
                $("#singFileName").html(data.data.name);
                $("#upload-ico").data('type', 'delete');
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
    }
     //原始文件拍照
    function photograph(){
        layer('openInvoice','photograph',{})
    }
    function setXformClass () {
		$('.xform').each(function(idx,el) {
			el.className = "xform x" + "-rotated-" + phi;
		});
	}
    // 旋转
    function roateImg(){
        phi = (phi + 90) % 360;
        setXformClass();
        if (phi % 180) {
            $('.xform-p').addClass('rotated');
        } else {
            $('.xform-p').removeClass('rotated');
        }
    }
    function delImg(e){
       $(e).parent().remove()
    }
    //拍照
   function GrabImageBase64() {
		var cutpage = document.getElementsByName("cutpage");  
		var params = "{\"filepath\":\"base64\",\"rotate\":\"" + phi.toString() + "\",\"camidx\":\"" + camidx.toString() + "\",\"cutpage\":\"" + (cutpage[0].checked ? "1" : "0") + "\"}";//
		var url = "http://127.0.0.1:38088/video=grabimage";  	
		$.ajax({  
			type: "post",  
			url: url,  
			dataType: "json", 
			data: params,
			success: function(data)
			{			
				$(".picture-list").append("<div style='padding:10px;position:relative'><img class='li-ico' style='width:200px' src='data:image/jpg;base64,"+data.photoBase64+"'><a style='position:absolute;top: 2px;right: 72px;' onclick='delImg(this)' href='javascript:void(0)'><div style='top:0;left:0'><span class='u-icon-delete'><i></i></span></div></a><input name='fileCode[]' type='hidden' value='data:image/jpg;base64,"+data.photoBase64+"'></div>")
			}  
			});  
	}
    	//初始化
	function Init(){
		GetResolution();
	}
	function GetResolution() {
		var params = "{\"type\": \"resolution\",\"camidx\":\"" + camidx.toString() + "\"}";//
		var url = "http://127.0.0.1:38088/param=get";  
		$.ajax({  
			type: "post",  
			url: url,  
			dataType: "json", 
			data: params,
			success: function(data)
			{
				if(data.code != 0)
				{
					 console.log("返回代码 = " + data.code + "<br />返回信息 = " + data.message)
				}
				else
				{
					var select = document.getElementById("resolution");
					//获取select下拉框下所有的选项
					while(select.options.length > 0)
					{
						select.remove(i);
					}
					
					var arrays = data.resolution.split("|");
					for(var i=0; i<arrays.length; i++)
					{
						select.options.add(new Option(arrays[i], arrays[i])); 
					}
				}  				
			}
		});  
	}
	function button_del(e, power = '') {
     let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
        let id = $(e).parent().find("[name='photoFileId']").val();
        $.post(url, {
            id: id, power: power
        }, function (res) {
            if (res.warn === 2) {
               $(e).parent().empty();
            } else {
                warn(res.warn);
            }
        }, 'json')
    }
    function addRow(){
        $.post(root+'control/adIndex.html?cla=openInvoice&fun=addSendOrderEdit',$("form[name='saleSendOrderForm']").serialize(),function(res) {
               $('#openInvoiceAddSendOrder').hide()
                $(".voucherTable .td-data").each(function() {
                    if(!$(this).find("[name='name[]']").val()){
                        $(this).remove()
                    }
                })
                $(".voucherTable tr").eq(1).after(res.html);
                 calculateTotal();
            },'json');
        }
</script>
eof;

    }

    /**
     * 添加一行
     */
    public function addRow(): bool|string
    {
        $addIco = root . 'img/control/v_add.svg';
        $delIco = root . 'img/control/v_del.svg';
        $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)'  style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'title' => '', 'value' => '')) . "</select>";
        $mxId = suiji();
        $json['html'] = <<<eof
<tr class="tr-data td-data center">
  <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value=""><div class="add_v_btn"><img src="{$addIco}"></div>
            <input name="name[]" id="$mxId" type="text" class="width_100"></td>
            <td><input name="model[]" type="text" class="width_100"></td>
            <td><input name="unit[]" type="text" class="width_100"></td>
            <td><input name="num[]" data-type="num" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td><input name="price[]" data-type="price" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td><input name="money[]" data-type="money" onblur="calculateMoney(this)" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$delIco}"></div></td>
      </tr>
<script>
        $("#{$mxId}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
              $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
eof;
        return json_encode($json, 320);
    }

    public function css()
    {
        return <<<eof
<style>
.width_100{width: 90%}
.switch_ico{width: 20px;height: 20px;margin-left: 5px;cursor: pointer}
.company-title-two{writing-mode:vertical-lr;letter-spacing:8px;width: 30px;height: 94px;font-size: 13px;}
.company-title-two>p{text-align: center;line-height: 30px}
.company-title{writing-mode:vertical-lr;letter-spacing:5px;width: 30px;height: 94px;font-size: 13px;border-right: 1px solid rgba(170, 170, 170, 1)}
.company-title>p{text-align: center;}
.template-input{height: 25px;padding: 0 5px}
.staffName{height: 40px;line-height: 40px}
.voucher-button{height: 50px}
.tip-component-other{margin-top: 5px;margin-right: 10px;width: 13px;height: 13px;line-height: 13px}
.input-div input{text-align: center}
.height23{height: 23px}
.voucherNo{width: 139px;height: 23px}
.tr-data td:first-child,.tr-data td:last-child{position: relative}
.add_v_btn{position: absolute;cursor: pointer;top: 2px;left: -17px;display: none}
.del_v_btn{position: absolute;cursor: pointer;right: -17px;top: 2px;display: none}
.add_v_btn img,.del_v_btn img{width: 20px;}
.td-title{display: flex;flex-direction: row;font-size: 13px}
.voucher-title{text-align: center;font-size: 18px;font-weight: bold}
.pageDiv,body{background-color: rgba(242, 242, 242, 1)}
.voucherTable{border-collapse: collapse;border-spacing: 0;text-align: center;font-size: 12px;margin-top: 10px}
.voucherTable td {border: 1px solid rgba(170, 170, 170, 1);border-spacing:0;padding: 0}
.voucherTable tr{cursor: pointer;font-size: 13px}
.bold{font-weight: bold}
.calendarBody{padding: 20px;background-color:rgba(232, 235, 244, 1);width: 960px;margin: 10px auto;color: #7B4D12}
.voucher-body{padding: 30px;background-color: rgba(242, 242, 242, 1)}
.calendarBody input{padding: 0 3px}
.moneyUnit span{
    float: left;
    display: inline;
    width: 19px;
    height: 100%;
    margin-right: 1px;
    background-color: #fff;
    text-align: center;
    font-size: 12px;
}
.pageDiv{
    background-color: white;
    padding: 0;
}
.pageMenu{margin: 10px 0 0;}
.pageMenu > ul {
    padding: 0 20px;
}
.pageMenu > ul > li {
    float: left;
    padding: 6px 10px;
    background-color: rgb(255, 255, 255);
    cursor: pointer;
}
.tr-border{border: 1px solid rgba(170, 170, 170, 1);}
.tr-data{width: 200px}
.tr-data td{border-bottom: none;padding: 3px 7px}
.tr-data td:nth-child(n+1){border-bottom: none;border-top: none;}
</style>
eof;

    }


    /**
     * 模糊查询客户
     * @return bool|string
     */
    public function getClient(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $json['data'] = [];
        $where = empty($val) ? "and 1=1" : "and (companyName like '%" . $val . "%' or orderNo like '%" . $val . "%')";
        $all = find(array('table' => 'kehu', 'where' => "coid = '" . self::$coid . "' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array(
                'title' => $val['companyName'],
                'companyNum' => $val['companyNum'],
                'companyAddress' => $val['companyAddress'],
                'companyBankNum' => $val['companyBankNum'],
                'companyBank' => $val['companyBank'],
                'orderNo' => $val['orderNo'],
                'id' => $val['khid']
            );
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }


    /**
     * 模糊查询员工
     */
    public function getStaff(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or orderNo like '%" . $val . "%')";
        $all = find(array('table' => 'staff', 'where' => "state != '离职' and workFlow = '已复核' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['name'], 'code' => $val['orderNo'], 'id' => $val['stid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 原始文件拍照
     * @return false|string
     */
    public function photograph()
    {
        $failIco = root . 'img/control/app_stop.jpg';
        $cla = self::page;
        $photos =L('finance.table.photos');
        $crop =L('finance.table.crop');
        $confirmButton =L('finance.table.confirmButton');

//        $rotate = root.'img/control/rotate.svg';
        //  <img title=L('finance.table.xuan_zhuan') alt=L('finance.table.xuan_zhuan') src="{$rotate}" onclick="roateImg()" style="width: 20px;margin-left: 20px;cursor: pointer;margin-top: -2px" id="rotate">
        //生成表单
        $html = <<<eof
<form name="photographForm">
<div class="photograph-body" onLoad="Init()">
    <div class="photograph-left">
        <div>
            <span class="spanButton li-btn-blue-bg" style="margin-left: 0" onclick="GrabImageBase64()">$photos</span>
            <span style="margin-left: 20px"><label class="checkbox"><input type="checkbox" name="cutpage" value="cutpage" checked><span></span>&nbsp;{$crop}</label></span>
          
        </div>
        <div style="margin-top: 20px">
            <p class="xform-p"></p>
            <p id="streamwrap" class="xform-p">
            <img id="streamimage" class="xform" src="http://127.0.0.1:38088/video=stream&camidx=0" onerror="onerror=null;src='$failIco'"/>
            </p>
        </div>
    </div>
    <div class="photograph-right">
        <div><span class="spanButton li-btn-blue-bg" onclick="commitPhotograph('photographForm',root+'control/adIndex.html?cla=$cla&fun=photographEdit')">$confirmButton</span></div>
        <div class="picture-list">
             
        </div>
    </div>
</div>
</form>
<style>

.photograph-body{display: flex;flex-direction: row}
.photograph-left{padding: 10px}
.photograph-right{width: 100%;padding: 10px;border-left: 1px solid #dadada}
.picture-list img{width: 200px;}
.picture-list{overflow-y: scroll;height: 455px;margin-top: 5px;text-align: center}
#streamimage{width: 430px;height: 430px}
img.x-rotated-0 {}
img.x-rotated-90 {
	-moz-transform: rotate(90deg);
	-webkit-transform: rotate(90deg);
}
img.x-rotated-180 {
	-moz-transform: rotate(180deg);
	-webkit-transform: rotate(180deg);
}
img.x-rotated-270 {
	-moz-transform: rotate(270deg);
	-webkit-transform: rotate(270deg);
}
img.x-mirrored-rotated-0 {
	-moz-transform: scaleX(-1);
	-webkit-transform: scaleX(-1);
}
img.x-mirrored-rotated-90 {
	-moz-transform: rotate(90deg) scaleX(-1);
	-webkit-transform: rotate(90deg) scaleX(-1);
}
img.x-mirrored-rotated-180 {
	-moz-transform: rotate(180deg) scaleX(-1);
	-webkit-transform: rotate(180deg) scaleX(-1);
}
img.x-mirrored-rotated-270 {
	-moz-transform: rotate(270deg) scaleX(-1);
	-webkit-transform: rotate(270deg) scaleX(-1);
}
img.x-flipped-rotated-0 {
	-moz-transform: scaleY(-1);
	-webkit-transform: scaleY(-1);
}
img.x-flipped-rotated-90 {
	-moz-transform: rotate(90deg) scaleY(-1);
	-webkit-transform: rotate(90deg) scaleY(-1);
}
img.x-flipped-rotated-180 {
	-moz-transform: rotate(180deg) scaleY(-1);
	-webkit-transform: rotate(180deg) scaleY(-1);
}
img.x-flipped-rotated-270 {
	-moz-transform: rotate(270deg) scaleY(-1);
	-webkit-transform: rotate(270deg) scaleY(-1);
}
img.x-flipped-mirrored-rotated-0 {
	-moz-transform: scale(-1,-1);
	-webkit-transform: scale(-1,-1);
}
img.x-flipped-mirrored-rotated-90 {
	-moz-transform: rotate(90deg) scale(-1,-1);
	-webkit-transform: rotate(90deg) scale(-1,-1);
}
img.x-flipped-mirrored-rotated-180 {
	-moz-transform: rotate(180deg) scale(-1,-1);
	-webkit-transform: rotate(180deg) scale(-1,-1);
}
img.x-flipped-mirrored-rotated-270 {
	-moz-transform: rotate(270deg) scale(-1,-1);
	-webkit-transform: rotate(270deg) scale(-1,-1);
}
</style>
eof;

        //返回
        return $this->layer(array("title" => L('finance.table.pai_zhao'), 'winFix' => true, "height" => 600, "width" => 845, "html" => $html));
    }

    /**
     * 高拍仪数据处理
     */
    public function photographEdit(): bool|string
    {
        $fileCodes = $this->post('fileCode');
        if (static::is_null_array($fileCodes)) {
            $json['warn'] = L('finance.table.wzdscwj');
        } elseif (count($fileCodes) > 1) {
            $json['warn'] = L('finance.table.znscyztp');
        } else {
            $json['warn'] = 2;
            $delIco = root . 'img/control/delete.svg';
            $url = 'file/' . self::page . "/" . date("Ym");
            $this->_mkdir($url);
            $html = '';
            $power = self::page;
            foreach ($fileCodes as $base64) {
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $res)) {
                    $suiji = suiji();
                    $src = $url . "/" . $suiji . ".jpg"; //保存附件的根目录路径
                    if (file_put_contents(serverRoot . $src, base64_decode(str_replace($res[1], '', $base64)))) {
                        $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' =>'发票原件', 'name' => '发票识别' . $suiji . '.jpg', 'format' => 'jpg', 'size' => filesize(serverRoot . $src), 'src' => $src);
                        $warn = insert(array('table' => 'file', 'field' => $field));
                        if ($warn == '新增成功') {
                            //$html = "<span id='singFileName' class='del-row-button'>{$field['name']}</span> <img data-type='delete' onclick=\"button_del(this,'$power')\"  id='upload-ico' src='$delIco' style='width: 22px;height: 22px;margin-left: 5px;cursor: pointer' alt=''/>" . hidden(array('name' => 'photoFileId', 'value' => $field['id']));
                            $json['data']['id'] = $field['id'];
                            $json['data']['src'] = root . $field['src'];
                            $json['data']['name'] = $field['name'];
                        }
                    }
                    break;
                }
            }
            $json['html'] = $html;
        }
        return json_encode($json, 320);
    }

    /**
     * 发票OCR识别
     */
    public function vatInvoiceOCR()
    {
        $cla = self::page;
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('finance.table.shuo_ming') => "
                <p>1、".L('finance.table.photosTextOne')."</p>
                <p>2、".L('finance.table.photosTextTwo')."</p>
                "
            ),
            array(
                L('finance.table.pai_zhao') => "<span class='spanButton' style='margin: 0' onclick='photograph()'>".L('finance.table.original')."</span><span id='photoFile'></span>"
            ),
            array(
                L('finance.table.fjsc') => fileUploadClass::singleUpload("{$cla}VatInvoiceOCRForm", self::page, '', '发票识别')
            ),
        )
        ));
        //返回
        return $this->layer(array(
            "title" => L('finance.table.scwj'),
            "height" => 315,
            "width" => 800,
            "html" => $html,
            'button' => "<input onclick=\"vatInvoiceOCR('{$cla}VatInvoiceOCRForm',root+'control/adIndex.html?cla=openInvoice&fun=vatInvoiceOCREdit')\" type='button' class='button' value='".L('finance.table.shi_bie')."'>"
        ));
    }

    /**
     * 发票OCR识别
     * @return false|string
     */
    public function vatInvoiceOCREdit()
    {
        $fileId = $this->post('fileId') ?: $this->post('photoFileId');
        $file = query('file', "id = '$fileId'");
        if (empty($fileId) || empty($file['id'])) {
            $json['warn'] = L('finance.table.wzdscdwj');
        } else {
            $tencent = new tencentApiClass();
            $result = $tencent->vatInvoiceOCR(root . $file['src']);
            $res = json_decode($result, true);
            if (isset($res['Response']['Error'])) {
                $json['warn'] = $res['Response']['Error']['Message'];
            } else {
                $dataTr = '';
                $fileTextArr = [
                    '销售方识别号' => 'SellerTaxCode',
                    '发票代码' => 'Code',
                    '发票号码' => 'Number',
                    '发票名称' => 'invoiceName',
                    '合计税额' => 'TaxAmount',
                    '合计金额' => 'AmountWithoutTax',
                    '复核' => 'checkName',
                    '密码区1' => 'secret1',
                    '密码区2' => 'secret2',
                    '密码区3' => 'secret3',
                    '密码区4' => 'secret4',
                    '小写金额' => 'AmountWithTax',
                    '开票人' => 'openName',
                    '开票日期' => 'Date',
                    '收款人' => 'receiveName',
                    '购买方名称' => 'BuyerName',
                    '购买方地址、电话' => 'BuyerAddressPhone',
                    '购买方开户行及账号' => 'BuyerBankAccount',
                    '购买方识别号' => 'BuyerTaxCode',
                    '销售方名称' => 'SellerName',
                    '销售方地址、电话' => 'SellerAddressPhone',
                    '销售方开户行及账号' => 'SellerBankAccount',
                    '备注' => 'Remark',
                ];
                $invoice = [];
                foreach ($fileTextArr as $name => $val) {
                    foreach ($res['Response']['VatInvoiceInfos'] as $array) {
                        if ($array['Name'] == $name) {
                            $invoice[$val] = $invoice[$val] ?? '';
                            $invoice[$val] .= ltrim($array['Value'], '¥');
                        }
                    }
                }
                $invoice['Date'] = str_replace(['年', '月', '日'], '-', $invoice['Date']);
                $invoice['Date'] = rtrim($invoice['Date'], '-');
                $invoice['Number'] = ltrim($invoice['Number'], 'No');
                foreach ($res['Response']['Items'] as $array) {
                    $mxId = suiji();
                    $array['TaxRate'] = rtrim($array['TaxRate'], '%');
                    $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)' data-type='tax' style='width: 80px;height: 22px'>" . option(array('option' => explode('，', para('taxRate')), 'value' => $array['TaxRate'])) . "</select>";
                    $dataTr .= <<<eof
<tr class="tr-data td-data center">
  <td><input name="mxId[]"  type="hidden" value="$mxId"><input type="hidden" name="sourceId[]" value=""><div class="add_v_btn"><img src="{$this->addIco}"></div><input name="name[]" id="$mxId" value="{$array['Name']}" type="text" class="width_100"></td>
            <td><input name="model[]" value="{$array['Spec']}" type="text" class="width_100"></td>
            <td><input name="unit[]" value="{$array['Unit']}" type="text" class="width_100"></td>
            <td><input name="num[]" onblur="calculateMoney(this)" data-type="num" value="{$array['Quantity']}" type="text" class="width_100"></td>
            <td><input name="price[]" onblur="calculateMoney(this)" data-type="price" value="{$array['UnitPrice']}" type="text" class="width_100"></td>
            <td><input name="money[]" onblur="calculateMoney(this)" data-type="money" value="{$array['AmountWithoutTax']}" type="text" class="width_100"></td>
            <td>$taxSelect</td>
            <td><input name="taxMoney[]" readonly value="{$array['TaxAmount']}" type="text" class="width_100"><div class="del_v_btn"><img src="{$this->delIco}"></div></td>
      </tr>
<script>
        $("#{$mxId}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
              $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
eof;
                }
                $json['data'] = [
                    'html' => $dataTr,
                    'info' => $invoice
                ];
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 关联销售发货单
     * @return bool|string
     */
    public function addSendOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => L('finance.table.xsfhdh'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('finance.table.dan_ju_ri_qi'))) .
            hidden(array('name' => 'khid', 'value' => $this->post('khid'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='".L('finance.table.ti_jiao')."'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('finance.table.tian_jia'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联销售发货单
     * @return bool|string
     */
    public function addSendOrderSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = "khid = '" . $this->post('khid') . "' and id not in (select distinct orderId from sale_send_order_detail where id in ('" . implode("','", $sourceId) . "'))";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
            'coid' => self::$coid,
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "sale_send_order",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("saleSendOrderForm", "saleSendOrderId");
        $tr[] = [$checkAll, L('finance.table.xsfhdh'), L('finance.table.dan_ju_ri_qi')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "saleSendOrderId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='saleSendOrderForm'>" .
                hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联销售发货单
     */
    public function addSendOrderEdit(): bool|string
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('saleSendOrderId');
        $isTax = $this->post('isTax');
        if (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('finance.table.qxzxsfhd');
        } else {
            $json['html'] = '';
            foreach ($mxIdArr as $saleSendOrderId) {
                $saleSendOrderMxAll = find(array('table' => "sale_send_order as a join sale_send_order_detail as b on a.id = b.orderId", 'where' => " a.id = '$saleSendOrderId' order by list asc", 'field' => "b.*,a.orderNo"));
                foreach ($saleSendOrderMxAll['array'] as $saleSendOrderMx) {
                    $material = query('material', "id = '$saleSendOrderMx[materialId]'");
                    //已进入到开票的销售发货单数量
                    $refundNum = find(array('table' => 'invoice_open_detail', 'where' => "orderId !='$id' and sourceId = '$saleSendOrderMx[id]' and coid = '" . self::$coid . "'", 'sum' => 'num'));
                    $num = ($saleSendOrderMx['num'] - $refundNum) > 0 ? ($saleSendOrderMx['num'] - $refundNum) : 0;
                    $price = $saleSendOrderMx['price'];
                    $moneyRes = saleOrderClass::isTax($num, $price, $saleSendOrderMx['rate'], $isTax);
                    $money = $moneyRes['money'];
                    $taxMoney = $moneyRes['taxMoney'];
                    $addIco = root . 'img/control/v_add.svg';
                    $delIco = root . 'img/control/v_del.svg';
                    $taxSelect = "<select name='tax[]' onchange='calculateMoney(this)'  style='width: 80px;height: 22px'>" . option(array('value' => $saleSendOrderMx['rate'] * 100, 'option' => explode('，', para('taxRate')), 'title' => '',)) . "</select>";
                    $suiji = self::getId();
                    $name = materialClass::getName($material['id'], '*');
                    $json['html'] .= <<<efo
                  <tr class="tr-data td-data center">
                        <td>
                            <input name="mxId[]"  type="hidden" value="$suiji">
                            <input name="sourceId[]" type="hidden" value="$saleSendOrderMx[id]">
                            <div class="add_v_btn"><img src="{$addIco}"></div>
                            <input name="name[]" id="$suiji" value="$name" type="text" class="width_100">
                        </td>
                        <td><input name="model[]" value="$material[model]" type="text" class="width_100"></td>
                        <td><input name="unit[]" value="{$material['unit']}" type="text" class="width_100"></td>
                        <td><input name="num[]" data-type="num" value="$num" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td><input name="price[]" data-type="price" value="$price" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td><input name="money[]" data-type="money" value="$money" onblur="calculateMoney(this)" type="text" class="width_100"></td>
                        <td>$taxSelect</td>
                        <td><input name="taxMoney[]" value="$taxMoney" readonly type="text" class="width_100"><div class="del_v_btn"><img src="{$delIco}"></div></td>
                  </tr>
<script>
        $("#{$suiji}").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=openInvoice&fun=getMaterial',
        callback:function(data,e){
            $(e).parent().parent().find("[name='model[]']").val(data.model);
             $(e).parent().parent().find("[name='unit[]']").val(data.unit);
        }
    });
</script>
efo;
                }
            }
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    public function getMaterial()
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where = empty($val) ? "and 1=1" : "and (b.code like '%" . $val . "%' or b.name like '%" . $val . "%')";
        $all = find(array(
            'table' => 'material as b',
            'field' => "b.id,b.unit,b.code,b.model,b.name as materialName",
            'where' => "b.coid = '" . self::$coid . "'  $where order by b.code limit 100"
        ));
        foreach ($all['array'] as $val) {
            $name = $val['code'] ? $val['code'] . '*' : '';
            $name .= $val['materialName'] ? $val['materialName'] . '*' : '';
            $name .= $val['model'] ? $val['model'] . '*' : '';
            $name = rtrim($name, '*');
            $json['data'][] = array('title' => $name, 'model' => $val['model'], 'unit' => $val['unit'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }
}

